const multer = require("@koa/multer");
const path = require("path");
let getTime = require("../utils/getTime");
var config = require("../config.js");
console.log(getTime.dateNow() + " " + getTime.timeNow());
let imgName = [];

//购物文件保存设置
const storageCart = multer.diskStorage({
  // destination: function (req, file, cb) {
  //   cb(null, path.join(__dirname, "/public"));
  // },
  // 文件保存路径, 这里需要自己手动到public下面新建upload文件夹。
  destination: function (req, file, cb) {
    cb(null, "public/upload/cart");
  },

  filename(req, file, cb) {
    // logger.debug(req);
    // console.log(file + Date.now());
    let fileFormat = file.originalname.split("."); //以点分割成数组，数组的最后一项就是后缀名
    //文件名字，时间+原文件名字
    let fileNowName =
      Number(Math.random().toString().substr(3, 6) + Date.now()).toString(36) +
      "." +
      fileFormat[fileFormat.length - 1];
    imgName.push(config.http + "cart/" + fileNowName);
    // BackApi.imgName(fileNowName);
    cb(null, fileNowName);
    // let type = file.originalname.split(".")[1];
    // cb(null, `${file.fieldname}-${Date.now().toString(16)}.${type}`);
  },
});
//购物文件上传限制
const limitsCart = {
  storage: storageCart,
  limits: {
    fileSize: 1024 * 1024 * 4, // 限制4m
  },
};
//购物
const uploadCart = multer({ storage: storageCart, limits: limitsCart });

//通用文件保存设置
const storage = multer.diskStorage({
  // destination: function (req, file, cb) {
  //   cb(null, path.join(__dirname, "/public"));
  // },
  // 文件保存路径, 这里需要自己手动到public下面新建upload文件夹。
  destination: function (req, file, cb) {
    cb(null, "public/upload");
  },

  filename(req, file, cb) {
    // logger.debug(req);
    // console.log(file + Date.now());
    let fileFormat = file.originalname.split("."); //以点分割成数组，数组的最后一项就是后缀名
    //文件名字，时间+原文件名字
    let fileNowName =
      Number(Math.random().toString().substr(3, 6) + Date.now()).toString(36) +
      "." +
      fileFormat[fileFormat.length - 1];

    imgName.push(config.http + fileNowName);

    // BackApi.imgName(fileNowName);
    cb(null, fileNowName);
    // let type = file.originalname.split(".")[1];
    // cb(null, `${file.fieldname}-${Date.now().toString(16)}.${type}`);
  },
});
//通用文件上传限制
const limits = {
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 4, // 限制4m
  },
};
const upload = multer({ storage, limits });
// console.log(imgName);
class BackApi {
  constructor() {
    this.name = "";
  }
  genID(length) {
    return Number(
      Math.random().toString().substr(3, length) + Date.now()
    ).toString(36);
  }
  backApi(router, mysql) {
    // const koa2Req = require("koa2-request");

    // 登录
    router.post("/b_login", async (ctx, next) => {
      const { user, password } = ctx.request.body;
      let data = await mysql.query(
        `select * from login where user='${user}' and password='${password}'`
      );
      let mesg = "off";
      if (data.length <= 0 || data == null) {
        mesg = "off";
      } else {
        mesg = "ok";
      }
      ctx.body = {
        mesg,
      };
    });
    // 开始本月上报
    router.post("/setDelete_pay_month", async (ctx, next) => {
      // console.log("dd");
      await mysql.delete("pay_month"); //删除表中全部数据
      let people_info = await mysql.select("all_needpay");
      // console.log(people_info[0].name);
      for (const i in people_info) {
        let name = people_info[i].name;
        let address = people_info[i].address;
        let openid = people_info[i].openid;
        mysql.query(
          `INSERT INTO pay_month (openid,name,address,water,electric,report_time,status,water_status,ele_status) VALUES ('${openid}', '${name}','${address}','-1','-1','-1','-1','-1','-1')`
        );
      }
      ctx.body = {
        mesg: "ok",
      };
    });
    // 删除已验证人员
    router.post("/change_pay_month", async (ctx, next) => {
      const { openid, water, electric, status, report_time } = ctx.request.body;

      mysql.query(
        `UPDATE pay_month SET water='${water}',electric='${electric}',status='${status}',report_time='${report_time}'  WHERE openid = '${openid}'`
      );
      ctx.body = {
        mesg: "ok",
      };
    });
    //上传图片, 获取图片名字返回;
    router.post("/add", upload.single("file"), async (ctx) => {
      // const { title, img, text } = ctx.request.body;
      console.log(imgName);
      let mesg = "ok";
      if (imgName.length == 0) {
        mesg = "off";
      }
      ctx.body = {
        mesg,
        imgName,
      };
      imgName = [];
    });
    //上传购物图片,获取图片名字返回
    router.post("/add_cart_img", uploadCart.single("file"), async (ctx) => {
      // const sort = ctx.request.header.sort;
      // console.log(sort);
      // console.log(imgName);
      let mesg = "ok";
      if (imgName.length == 0) {
        mesg = "off";
      }
      ctx.body = {
        mesg,
        imgName,
        img: "购物",
      };
      // console.log("yic");
      // console.log(imgName);
      imgName = [];
    });
    //上传购物图片,图文,获取图片名字返回
    router.post("/add_cart_item", async (ctx) => {
      const {
        s_id,
        title,
        price,
        sort,
        place,
        guige,
        shelfLife,
        howSave,
        itemImg,
        tuWenImg,
      } = ctx.request.body;
      // console.log("tuwen");
      // let time = getTime.dateNow() + " " + getTime.timeNow();
      let time = getTime.dateNow() + " " + getTime.timeNow();
      await mysql.query(
        `INSERT INTO cart (s_id,title,price,sort,place,guige,shelf_life,how_save,item_img,tuwen_img,time) VALUES ('${s_id}','${title}','${price}','${sort}','${place}','${guige}','${shelfLife}','${howSave}','${itemImg}','${tuWenImg}','${time}')`
      );
      // let data = await mysql.query("select * from cart");
      ctx.body = {
        mesg: "ok",
        // data,
      };
    });
    //修改改购物商品
    router.post("/up_cart_item", async (ctx) => {
      const { s_id, title, price, sort, place, guige, shelfLife, howSave } =
        ctx.request.body;
      // console.log("tuwen");
      let time = getTime.dateNow() + " " + getTime.timeNow();
      await mysql.query(
        `UPDATE cart SET title='${title}',price='${price}',sort='${sort}',place='${place}',guige='${guige}',shelf_life='${shelfLife}',how_save='${howSave}',time='${time}' where s_id ='${s_id}'`
      );
      // let data = await mysql.query("select * from cart");
      ctx.body = {
        mesg: "ok",
        // data,
      };
    });
    //删除特定购物商品
    router.post("/delete_cart_item", async (ctx) => {
      const { s_id } = ctx.request.body;
      // console.log("tuwen");
      // let time = getTime.dateNow() + " " + getTime.timeNow();
      //购物列表和购物车中全删除
      await mysql.query(`DELETE FROM cart WHERE s_id = '${s_id}'`);
      await mysql.query(`DELETE FROM cart_one WHERE s_id = '${s_id}'`);
      // let data = await mysql.query("select * from cart");
      ctx.body = {
        mesg: "ok",
        // data,
      };
    });
    //购物订单确认
    router.post("/set_cart_order", async (ctx) => {
      const { id, date } = ctx.request.body;
      // console.log("tuwen");
      // let time = getTime.dateNow() + " " + getTime.timeNow();
      await mysql.query(
        `update cart_order set status='1',t_date='${date}' WHERE id = '${id}'`
      );
      // let data = await mysql.query("select * from cart");
      ctx.body = {
        mesg: "ok",
        // data,
      };
    });
    //新闻存入存入数据库
    router.post("/add-news", async (ctx) => {
      const { title, img, text } = ctx.request.body;
      console.log();
      const date = getTime.dateNow();
      if (img == "无") {
        mysql.query(
          `INSERT INTO news (title,img,text,date) VALUES ('${title}','无','${text}','${date}')`
        );
      } else {
        mysql.query(
          `INSERT INTO news (title,img,text,date) VALUES ('${title}','${img}','${text}','${date}')`
        );
      }
      ctx.body = {
        mesg: "ok",
      };
    });
    // 删除一个新闻
    router.post("/delete_news", async (ctx, next) => {
      const { id } = ctx.request.body;
      mysql.query(`DELETE FROM news WHERE id = '${id}'`);
      ctx.body = {
        mesg: "ok",
      };
    });
    //公告存入存入数据库
    router.post("/add_notice", async (ctx) => {
      const { title, img, text } = ctx.request.body;
      console.log();
      const date = getTime.dateNow();
      if (img == "无") {
        await mysql.query(
          `INSERT INTO notices (title,img,text,date) VALUES ('${title}','无','${text}','${date}')`
        );
      } else {
        await mysql.query(
          `INSERT INTO notices (title,img,text,date) VALUES ('${title}','${img}','${text}','${date}')`
        );
      }
      ctx.body = {
        mesg: "ok",
      };
    });
    // 删除一个公告
    router.post("/delete_notice", async (ctx, next) => {
      const { id } = ctx.request.body;
      mysql.query(`DELETE FROM notices WHERE id = '${id}'`);
      ctx.body = {
        mesg: "ok",
      };
    });
    //修改投诉举报状态
    router.post("/up_complaint", async (ctx, next) => {
      const { id } = ctx.request.body;

      // //注入个人投诉举报记录
      // await mysql.query(
      //   `INSERT INTO complaint (openid,ele_time,water_time,name,address,water,electric) VALUES ('${openid}','${time}', '${name}','${address}','${water}','${electric}')`
      // );
      //注入全部投诉举报记录
      await mysql.query(
        `UPDATE complaint SET all_state='1' WHERE id = '${id}'`
      );
      ctx.body = {
        mesg: "ok",
      };
    });
    //修改报修举报状态
    router.post("/up_repaire", async (ctx, next) => {
      const { id } = ctx.request.body;

      // //注入个人投诉举报记录
      // await mysql.query(
      //   `INSERT INTO complaint (openid,ele_time,water_time,name,address,water,electric) VALUES ('${openid}','${time}', '${name}','${address}','${water}','${electric}')`
      // );
      //注入全部投诉举报记录
      await mysql.query(`UPDATE repaire SET all_state='1' WHERE id = '${id}'`);
      ctx.body = {
        mesg: "ok",
      };
    });
    //注入所有人员
    router.post("/set_all_people", async (ctx, next) => {
      const { openid, name, age, gender, phoneNum, address } = ctx.request.body;

      await mysql.query(
        `INSERT INTO all_people (openid, name,age,gender,phone,address) VALUES ('${openid}','${name}','${age}','${gender}','${phoneNum}','${address}')`
      );
      await mysql.query(`DELETE FROM people_info WHERE openid = '${openid}'`);
      ctx.body = {
        mesg: "ok",
      };
    });
    //根据openid删除全部人员指定
    router.post("/delete_all_people", async (ctx, next) => {
      const { openid } = ctx.request.body;

      await mysql.query(`DELETE FROM all_people WHERE openid = '${openid}'`);
      await mysql.query(`DELETE FROM all_needpay WHERE openid = '${openid}'`);
      ctx.body = {
        mesg: "ok",
      };
    });
    //注入所有需要支付人员
    router.post("/set_all_needpay", async (ctx, next) => {
      const { openid, name, gender, phoneNum, address } = ctx.request.body;
      await mysql.query(
        `INSERT INTO all_needpay (openid, name,gender,phone,address) VALUES ('${openid}','${name}','${gender}','${phoneNum}','${address}')`
      );
      await mysql.query(
        `DELETE FROM all_needpay_info WHERE openid = '${openid}'`
      );
      ctx.body = {
        mesg: "ok",
      };
    });
    //根据openid删除一个要支付人员
    router.post("/delete_all_needpay", async (ctx, next) => {
      const { openid } = ctx.request.body;
      await mysql.query(`DELETE FROM all_needpay WHERE openid = '${openid}'`);
      ctx.body = {
        mesg: "ok",
      };
    });
    //防疫知识存入存入数据库
    router.post("/add_prevention_knowledge", async (ctx, next) => {
      const { title, img, text } = ctx.request.body;
      // console.log();
      const date = getTime.dateNow();
      if (img == "无") {
        mysql.query(
          `INSERT INTO prevention_knowledge (title,img,text,date) VALUES ('${title}','无','${text}','${date}')`
        );
      } else {
        mysql.query(
          `INSERT INTO prevention_knowledge (title,img,text,date) VALUES ('${title}','${img}','${text}','${date}')`
        );
      }
      ctx.body = {
        mesg: "ok",
      };
    });
    // 删除一个防疫知识
    router.post("/delete_prevention_knowledge", async (ctx, next) => {
      const { id } = ctx.request.body;
      mysql.query(`DELETE FROM prevention_knowledge WHERE id = '${id}'`);
      ctx.body = {
        mesg: "ok",
      };
    });

    //问卷调查存入数据库
    router.post("/add_ques_con_list", async (ctx, next) => {
      const { name, optionOneAll } = ctx.request.body;
      // console.log();
      const options = JSON.stringify(optionOneAll);
      const q_id = this.genID(6);

      const date = getTime.dateNow();
      //注入全部问卷题数据库
      await mysql.query(
        `INSERT INTO ques_con_list (q_id,q_name,options) VALUES ('${q_id}','${name}','${options}')`
      );
      //注入问卷列表数据库
      await mysql.query(
        `INSERT INTO ques_name_list (q_id,q_name,date) VALUES ('${q_id}','${name}','${date}')`
      );
      // let data = await mysql.select("ques_con_list");
      ctx.body = {
        mesg: "ok",
      };
    });
    // 删除一个问卷调查,从三个数据库表中都删除
    router.post("/delete_ques", async (ctx, next) => {
      const { qId } = ctx.request.body;
      await mysql.query(`DELETE FROM ques_con_list WHERE q_id = '${qId}'`);
      await mysql.query(`DELETE FROM ques_name_list WHERE q_id = '${qId}'`);
      await mysql.query(`DELETE FROM ques_people_rep WHERE q_id = '${qId}'`);
      ctx.body = {
        mesg: "ok",
      };
    });
    // 后台获取单道题问卷题目
    router.post("/ques_con_list_one", async (ctx, next) => {
      const { qId } = ctx.request.body;
      let data = await mysql.query(
        `SELECT * FROM ques_con_list WHERE q_id = '${qId}'`
      );

      ctx.body = {
        mesg: "ok",
        data,
      };
    });
    // 后台获取一道小题目的全部答题情况
    router.post("/ques_people_one", async (ctx, next) => {
      const { optionId } = ctx.request.body;
      let data = await mysql.query(
        `SELECT * FROM ques_people_rep WHERE option_id = '${optionId}'`
      );

      ctx.body = {
        mesg: "ok",
        data,
      };
    });
    // router.post("/tes", async (ctx, next) => {
    //   let data = await mysql.query(`select * from go_out_go where id = '1'`);
    //   console.log(data[0].dest);
    //   // await mysql.query(
    //   //   `INSERT INTO go_out_go (q_id,q_name,options) VALUES ('${q_id}','${name}','${options}')`
    //   // );

    //   ctx.body = {
    //     mesg: "ok",
    //     data,
    //   };
    // });
    //修改通过不通过，外出
    router.post("/change_go_out_go", async (ctx, next) => {
      const { openid, id, state } = ctx.request.body;
      await mysql.query(
        `UPDATE go_out_go SET state='${state}' WHERE id = ${id}`
      );
      if (state == 1) {
        let data = await mysql.query(
          `select * from go_out_go where id = '${id}'`
        );
        let name = data[0].name;
        let phone = data[0].phone;
        let trans = data[0].trans;
        let dest = data[0].dest;
        let time = data[0].time;
        await mysql.query(
          `INSERT INTO go_out_go_list (openid,name,phone,trans,dest,time,state) VALUES ('${openid}','${name}', '${phone}','${trans}','${dest}','${time}','申请')`
        );
        // await mysql.query(
        //   `INSERT INTO go_out_go (q_id,q_name,options) VALUES ('${q_id}','${name}','${options}')`
        // );
      }
      ctx.body = {
        mesg: "ok",
      };
    });
    //修改通过不通过，返回
    router.post("/change_go_out_out", async (ctx, next) => {
      const { id, openid, state } = ctx.request.body;
      await mysql.query(
        `UPDATE go_out_out SET state='${state}' WHERE id = '${id}'`
      );
      if (state == 1) {
        let data = await mysql.query(
          `select * from go_out_out where id = '${id}'`
        );
        let name = data[0].name;
        let phone = data[0].phone;
        let trans = data[0].trans;
        let now_address = data[0].now_address;
        let go_time = data[0].go_time;
        let arrive_time = data[0].arrive_time;
        let way = data[0].way;
        await mysql.query(
          `INSERT INTO go_out_out_list (openid,name,phone,trans,now_address,go_time,arrive_time,way,state) VALUES ('${openid}','${name}', '${phone}','${trans}','${now_address}','${go_time}','${arrive_time}','${way}','申请')`
        );
        // await mysql.query(
        //   `INSERT INTO go_out_go (q_id,q_name,options) VALUES ('${q_id}','${name}','${options}')`
        // );
      }
      ctx.body = {
        mesg: "ok",
      };
    });
    // 获得所有已验证人员信息
    router.get("/people-all", async (ctx, next) => {
      let data = await mysql.select("all_people");
      // console.log(err);
      ctx.body = {
        code: 1,
        data: data,
        mesg: "ok",
      };
    });

    //获得所有待验证人员信息
    router.get("/people-info", async (ctx, next) => {
      let data = await mysql.select("people_info");
      // console.log(err);
      ctx.body = {
        code: 1,
        data: data,
        mesg: "ok",
      };
    });

    router.get("/pay-month", async (ctx, next) => {
      let data = await mysql.select("pay_month");
      // console.log(err);
      ctx.body = {
        code: 1,
        data: data,
        mesg: "ok",
      };
    });

    router.get("/pay-delect", async (ctx, next) => {
      let data = await mysql.payDelete();
      // console.log(err);
      ctx.body = {
        code: 1,
        mesg: "ok",
      };
    });
    //后台获取投诉举报情况
    router.get("/b-complaint", async (ctx, next) => {
      let data = await mysql.select("complaint");
      // console.log(err);
      ctx.body = {
        mesg: "ok",
        data,
      };
    });
    //后台获取报修情况
    router.get("/b-repaire", async (ctx, next) => {
      let data = await mysql.select("repaire");
      // console.log(err);
      ctx.body = {
        mesg: "ok",
        data,
      };
    });
    //后台温度上报信息,每天
    router.get("/b-tem-report", async (ctx, next) => {
      let data = await mysql.select("tem_today_report");
      // console.log(err);
      ctx.body = {
        mesg: "ok",
        data,
      };
    });
    //后台温度上报信息,全部记录
    router.get("/b-tem-report-list", async (ctx, next) => {
      let data = await mysql.select("tem_report_list");
      // console.log(err);
      ctx.body = {
        mesg: "ok",
        data,
      };
    });
    //获得所有已缴费信息
    router.get("/pay-list", async (ctx, next) => {
      let data = await mysql.select("pay_list");
      // console.log(err);
      ctx.body = {
        code: 1,
        data: data,
        mesg: "ok",
      };
    });
    //获得新闻列表,前端也有新闻端口/news
    router.get("/news-list", async (ctx, next) => {
      let data = await mysql.select("news");
      // console.log(err);
      ctx.body = {
        code: 1,
        data: data,
        mesg: "ok",
      };
    });
    //后台户主申请表
    router.get("/all-needpay-info", async (ctx, next) => {
      let data = await mysql.select("all_needpay_info");
      // console.log(err);
      ctx.body = {
        mesg: "ok",
        data,
      };
    });
    //后台户主通过表
    router.get("/all-needpay", async (ctx, next) => {
      let data = await mysql.select("all_needpay");
      // console.log(err);
      ctx.body = {
        mesg: "ok",
        data,
      };
    });
    //后台获取防疫知识表内容
    router.get("/prevention-knowledge", async (ctx, next) => {
      let data = await mysql.select("prevention_knowledge");
      // console.log(err);
      ctx.body = {
        mesg: "ok",
        data,
      };
    });
    //答题题目列表
    router.get("/b-ques-name-list", async (ctx, next) => {
      //distinct 去除相同的
      let data = await mysql.select("ques_name_list");
      ctx.body = {
        mesg: "ok",
        data,
      };
    });
    //答题总人数
    router.get("/ques-people-num", async (ctx, next) => {
      //distinct 去除相同的
      let data = await mysql.query(
        "select distinct openid from ques_people_rep "
      );
      ctx.body = {
        mesg: "ok",
        peopleNum: data.length,
      };
    });
    //外出申请
    router.get("/b-go-out-go", async (ctx, next) => {
      //distinct 去除相同的
      let data = await mysql.select("go_out_go");
      ctx.body = {
        mesg: "ok",
        data,
      };
    });
    //返回申请
    router.get("/b-go-out-out", async (ctx, next) => {
      //distinct 去除相同的
      let data = await mysql.select("go_out_out");
      ctx.body = {
        mesg: "ok",
        data,
      };
    });
    //外出记录
    router.get("/b-go-out-go-list", async (ctx, next) => {
      //distinct 去除相同的
      let data = await mysql.select("go_out_go_list");
      ctx.body = {
        mesg: "ok",
        data,
      };
    });
    //返回记录
    router.get("/b-go-out-out-list", async (ctx, next) => {
      //distinct 去除相同的
      let data = await mysql.select("go_out_out_list");
      ctx.body = {
        mesg: "ok",
        data,
      };
    });
    //获取公告列表
    router.get("/b-notice-list", async (ctx, next) => {
      let data = await mysql.select("notices");
      // console.log(err);
      ctx.body = {
        data,
        mesg: "ok",
      };
    });
    //获取商品咧白哦
    router.get("/b-cart-list", async (ctx, next) => {
      let data = await mysql.select("cart");
      // console.log(err);
      ctx.body = {
        data,
        mesg: "ok",
      };
    });
    //获取商品咧白哦
    router.get("/b-cart-order", async (ctx, next) => {
      let data = await mysql.select("cart_order");
      // console.log(err);
      ctx.body = {
        data,
        mesg: "ok",
      };
    });
    router.get("/te3", async (ctx, next) => {
      //distinct 去除相同的
      let data = await mysql.select("cart");
      ctx.body = {
        mesg: "ok",
        data,
      };
    });
  }
}
module.exports = new BackApi();
// module.exports = BackApi;
